import re
from werkzeug.security import generate_password_hash
from flask import render_template, current_app, request, jsonify, redirect, url_for, session
from . import user_bp
from create_app import redis_pool
from models import User


@user_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form.get('email')
        password = request.form.get('pwd')
        obj = User.get(id=None, email=email)
        if not obj:
            return jsonify({'status': False, 'message': '用户不存在'})
        if not obj.check_password(password):
            return jsonify({'status': False, 'message': '密码不正确'})
        session['login_user'] = 'xxx'
        return jsonify({'status':True})
    return render_template('login.html')


@user_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':

        email = request.form.get('email')
        pwd = request.form.get('pwd')
        pwd2 = request.form.get('pwd2')
        if str(pwd) != str(pwd2):
            return jsonify({'status': False, 'message': '两次密码输入不一致'})
        if not re.match('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
            return jsonify({'status': False, 'message': '邮箱格式不正确'})
        username = email
        password_hash = generate_password_hash(pwd)
        result = User.add({'username': username, 'email': email, 'password_hash': password_hash})
        if result:
            return jsonify({'status': True, 'id': result})
        else:
            return jsonify({'status': False, 'message': '数据写入错误'})
    return render_template('register.html')


@user_bp.route('/test')
def test():
    pool.set('xxx', 1231324)
    current_app.logger.debug('evyejasjkgdsdhjk is ok!')
    current_app.logger.info('evyejasjkgdsdhjk is ok!')
    current_app.logger.warning('evyejasjkgdsdhjk is ok!')
    current_app.logger.error('evyejasjkgdsdhjk is ok!')
    current_app.logger.critical('evyejasjkgdsdhjk is ok!')
    return pool.get('xxx')
